package com.bwie.es.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bwie.common.domain.po.Goods;
import com.bwie.common.domain.vo.GoodsVo;
import com.bwie.common.result.PageResult;
import com.bwie.common.result.Result;
import com.bwie.common.utils.StringUtils;
import com.bwie.es.feign.EsFeign;
import com.bwie.es.service.EsService;
import lombok.extern.log4j.Log4j2;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Log4j2
public class EsServiceImpl implements EsService {
    @Autowired
    private EsFeign esFeign;
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    public static final String INDEX_NAME="goods";

    @Override
    public void batchAdd(List<Goods> goodss) {
          try {
              BulkRequest bulkRequest = new BulkRequest();
            goodss.forEach(goods -> {
                bulkRequest.add(
                    new IndexRequest(INDEX_NAME)
                            .id(goods.getGoodsId()+"")
                            .source(JSONObject.toJSONString(goods), XContentType.JSON)
                );
            });
            restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        }catch (Exception ex){
            log.error("");
        }
    }



    @Override
    public Result<PageResult<Goods>> search(GoodsVo goodsVo) {
        long total =0;
        ArrayList<Goods> goods1 = new ArrayList<>();
        try {
            SearchRequest searchRequest = new SearchRequest(INDEX_NAME);
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

            if(StringUtils.isNotBlank(goodsVo.getGoodsName())) {
                boolQueryBuilder.must(QueryBuilders.matchQuery("goodsName",goodsVo.getGoodsName()));
            }

            searchSourceBuilder.query(boolQueryBuilder);
            searchSourceBuilder.from((goodsVo.getPageNum()-1)*goodsVo.getPageSize());
            searchSourceBuilder.size(goodsVo.getPageSize());
            searchSourceBuilder.sort("goodsTime", SortOrder.DESC);
            searchSourceBuilder.highlighter(
                    new HighlightBuilder().field("goodsName")
                            .preTags("<font style=\"color:red;\">")
                            .postTags("</font>")
            );

            searchRequest.source(searchSourceBuilder);
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

            SearchHits hits = searchResponse.getHits();
            total=hits.getTotalHits().value;
            SearchHit[] searchHits = hits.getHits();
            for (SearchHit searchHit : searchHits) {
                String sourceAsString = searchHit.getSourceAsString();
                Goods goods = JSONObject.parseObject(sourceAsString, Goods.class);
                Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
                if(highlightFields!=null){
                    HighlightField highlightField = highlightFields.get("goodsName");
                    if(highlightField!=null){
                        Text[] fragments = highlightField.fragments();
                        StringBuilder sb = new StringBuilder();
                        for (Text fragment : fragments) {
                            sb.append(fragment);
                        }
                        goods.setGoodsName(sb.toString());
                    }
                }
                goods1.add(goods);
            }
        }catch (Exception ex){
            log.error("动态信息错误",JSONObject.toJSONString(goods1),ex);
        }
        return PageResult.toResult(total,goods1);
    }
}

